import { gql } from 'graphql-request';
import graphQLClient from '../index';

async function getUserById(id,selection={
  user:['id','name'],label:[],article:[]
}){

  const query = gql`
  query getUser($id:Int!){
    user(id:$id){
      ${selection.user.join()}
      ${selection.label&&selection.label.length>0?`
      _labels{
        ${selection.label.join()}
      }
      `:''}
      ${selection.article&&selection.article.length>0?`
      _articles{
        ${selection.article.join()}
      }
      `:''}
    }
  }`

  return await graphQLClient.request(query,{
    id
  })
}

async function getUsers(selection={
  user:['id','name'],label:[],article:[]
},page={
  current:0,
  size:5
},where={},sort={}){

  const query = gql`
  query getUsers($page:PageInput,$sort:UserSortInput,$where:UserWhereInput){
    users(page:$page,sort:$sort,where:$where){
      page{
        current,size,total
      }
      users{
        ${selection.user.join()}
        ${selection.label&&selection.label.length>0?`
        _labels{
          ${selection.label.join()}
        }
        `:''}
        ${selection.article&&selection.article.length>0?`
        _articles{
          ${selection.article.join()}
        }
        `:''}
      }
    }
  }`

  return await graphQLClient.request(query,{
    page,sort,where
  })
}

async function addUser(user){
  const mutation = gql`
  mutation addUser($user:UserInput!){
    addUser(user:$user){
      id,name
    }
  }`

  return await graphQLClient.request(mutation,{
    user
  })
}

async function modifyUserById(id,user){
  const mutation = gql`
  mutation modifyUser($id:Int!,$user:UserInput!){
    modifyUser(id:$id,user:$user){
      id,name
    }
  }`

  return await graphQLClient.request(mutation,{
    id,user
  })
}

async function removeUser(id){
  const mutation = gql`
  mutation removeUser($id:Int!){
    removeUser(id:$id){
      id,name
    }
  }`

  return await graphQLClient.request(mutation,{
    id
  })
}


export {
  getUserById,addUser,modifyUserById,removeUser,getUsers
}